#!/bin/env python
#coding=utf-8
# 0 表示正常  非0异常
import sys
import os
import time
import json
import subprocess

try:
    import json
except ImportError:
    import simplejson as json

def write_file(**kwargs):
    config =  kwargs.get('config')
    with  open(config.get('interface_monitor_file'), "w+") as f:
        reformat = json.dumps(config, sort_keys=True, indent=4)
        f.write(reformat)

def read_file(**kwargs):
    config =  kwargs.get('config')
    with  open(config.get('interface_monitor_file'), "r") as f:
        reformat = f.read()
    core_time_count_dict = json.loads(reformat)
    return core_time_count_dict

def main():
    # inter_face = 'enp2s0'
    inter_face = sys.argv[1]
    # print inter_face
    now_time = int(time.time())
    alarm_time = 24 * 60 * 60
    return_value = 0

    interface_monitor_file = '/tmp/zabbix_interface_monitor' + inter_face

    cmd_str = "ip link |grep '%s'|grep -c 'DOWN'" % inter_face
    cmd = subprocess.Popen(cmd_str, shell=True,
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = cmd.communicate()
    # print out
     
    inter_face_statu = out.strip()

    config = dict(
        interface_monitor_file = interface_monitor_file,
        inter_face_statu = inter_face_statu,
        monitor_time = now_time,
    )

    if not os.path.exists(interface_monitor_file):
        config['monitor_time'] = 0
        write_file(config=config)
        return_value = 0
    else:
        last_config = read_file(config=config)
        delta_time = now_time - last_config.get('monitor_time')

        if inter_face_statu != last_config.get('inter_face_statu'):
            write_file(config=config)
            return_value = inter_face_statu
        elif delta_time < alarm_time:
            return_value = inter_face_statu
    return return_value

if __name__ == '__main__':
    print main()